﻿/********************************************************************
	created:	2011/05/12
	created:	12:5:2011   22:09
	filename: 	D:\My Documents\Visual Studio 2010\Projects\IntranetMessager\ServiceLibrary\DataManagement.cs
	file path:	D:\My Documents\Visual Studio 2010\Projects\IntranetMessager\ServiceLibrary
	file base:	DataManagement
	file ext:	cs
	author:		
	
	purpose:	数据库操作中间层
*********************************************************************/
using System;
using System.Linq;

namespace ServiceLibrary
{
    internal static class DataManagement
    {
        internal static void DatabaseTest()
        {
            string str;
            using (var db = new DatabaseRepositoryDataContext())
            {
                str = db.DatabaseExists() ? "OK" : "Failed: Database error";
            }
            ServiceRepository.Printf("Model - Database - init " + str);
        }

        internal static bool AddNewAccount(string name, string passwd, string sessionId,
                                           out int newUid)
        {
            string desIv, desKey;
            CryptoService.DesGenerateKey(out desKey, out desIv);

            var newUser = new UserInfo
                              {
                                  Name = name,
                                  Password = sessionId,
                                  DES_Key = desKey,
                                  DES_IV = desIv
                              };
            using (var db = new DatabaseRepositoryDataContext())
            {
                try
                {
                    db.UserInfos.InsertOnSubmit(newUser);
                    db.SubmitChanges();
                    newUid = db.UserInfos.Single(x => x.Password == sessionId).UID;

                    return ModifyPassword(newUid, sessionId, passwd);
                }
                catch (Exception ex)
                {
                    newUid = -1;
                    ServiceRepository.Printf("Add new user error", ex, newUid);
                    return false;
                }
            }
        }

        internal static bool ComparePassword(int uid, string passwd)
        {
            using (var db = new DatabaseRepositoryDataContext())
            {
                return db.UserInfos.SingleOrDefault(x => x.UID == uid) != null
                       && String.Compare(passwd, db.UserInfos.SingleOrDefault(x => x.UID == uid).Password, false) == 0;
            }
        }

        private static bool ModifyPassword(int uid, string oldPassword, string newPassword)
        {
            using (var db = new DatabaseRepositoryDataContext())
            {
                try
                {
                    string passwd = db.UserInfos.Single(x => x.UID == uid).Password;
                    if (passwd == oldPassword)
                    {
                        db.UserInfos.Single(x => x.UID == uid).Password = newPassword;
                        db.SubmitChanges();
                        return true;
                    }
                    return false;
                }
                catch (Exception ex)
                {
                    ServiceRepository.Printf("Modify user password error", ex, uid);
                    return false;
                }
            }
        }

        internal static bool DesKeySaver(int uid, string key, string iv)
        {
            using (var db = new DatabaseRepositoryDataContext())
            {
                try
                {
                    db.UserInfos.Single(x => x.UID == uid).DES_Key = key;
                    db.UserInfos.Single(x => x.UID == uid).DES_IV = iv;
                    db.SubmitChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    ServiceRepository.Printf("Save user's Des key error", ex);
                    return false;
                }
            }
        }

        internal static void DesKeyLoader(int uid, out string key, out string iv)
        {
            using (var db = new DatabaseRepositoryDataContext())
            {
                try
                {
                    key = db.UserInfos.Single(x => x.UID == uid).DES_Key;
                    iv = db.UserInfos.Single(x => x.UID == uid).DES_IV;
                    return;
                }
                catch (Exception ex)
                {
                    key = null;
                    iv = null;
                    ServiceRepository.Printf("Save user's Des key error", ex);
                    return;
                }
            }
        }

        internal static int[] QueryUserIds(string name)
        {
            using (var db = new DatabaseRepositoryDataContext())
            {
                IQueryable<int> users = from result in db.UserInfos
                                        where result.Name.Contains(name)
                                        select result.UID;
                return users.ToArray();
            }
        }

        internal static string QueryUserName(int uid)
        {
            using (var db = new DatabaseRepositoryDataContext())
            {
                try
                {
                    return db.UserInfos.Single(x => x.UID == uid).Name;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
    }
}